<?php

namespace app\service;

use app\model\XMLModel;
use think\facade\Log;

class DealWithXMLService extends BaseService
{
    protected MinioService $minioService;
    protected string $filePath;
    protected array $dirList;
    protected array $localFileList;
    protected array $minioFileList;
    protected array $result;
    protected XMLModel $XMLModel;

    protected function initialize()
    {
        $this->XMLModel = new XMLModel();
        $this->minioService = new MinioService();
        $this->filePath = config("env.xml_path",false);
        if(!is_dir($this->filePath)) {
            Log::error(date("Y-m-d H:i:s") . " 弹幕文件（XML）位置配置错误，请检查");
            throw new \Exception(" 弹幕文件（XML）位置配置错误，请检查");
        }
        $this->dirList = $this->getDirectoryList();
        $this->localFileList = $this->getLocalFileList($this->dirList);
        $this->minioFileList = $this->getMinioFileList($this->dirList);
        $this->xmlExist();
        return $this->result;
    }

    /**
     * 获取本地目录列表
     * @return bool|array
     */
    protected function getDirectoryList(): bool|array
    {
        $list = scandir($this->filePath);
        foreach ($list as $key => $value) {
            if(preg_match("/^\.{1,2}$/",$value)) {
                unset($list[$key]);
                continue;
            }
            if(!is_dir($this->filePath."/".$value)) {
                unset($list[$key]);
                continue;
            }
            $list[$key] = $this->filePath.$value;
        }
        return $list;
    }

    /**
     * 获取本地文件列表
     * @param array $list
     * @return array
     */
    public function getLocalFileList(array $list): array
    {
        $fileList = [];
        foreach ($list as $value) {
            if(is_dir($value)) {
                $list = scandir($value);
                foreach ($list as $key1 => $value1) {
                    if(preg_match("/^\.{1,2}$/",$value1)) {
                        unset($list[$key1]);
                    }else {
                        $list[$key1] = basename($value) . "/" . $value1;
                    }
                }
                $fileList[basename($value)] = $list;
            }
        }
        return $fileList;
    }

    /**
     * 获取minio中的文件列表
     * @param array $list
     * @return array
     */
    public function getMinioFileList(array $list): array
    {
        foreach ($list as $key => $value) {
            $list[$key] = basename($value);
        }
        $fileList = [];
        try {
            $buckets = array_column($this->minioService->getBucketsList(),"Name");
            if(!in_array("xml",$buckets)) {
                $this->minioService->createBucket("xml");
            }
            foreach ($list as $value) {
                $fileList[$value] = $this->minioService->getFileList($value);
            }
            return $fileList;
        } catch (\Exception $e) {
            Log::error(date("Y-m-d H:i:s")." ".$e->getMessage());
            return [];
        }
    }

    /**
     * 验证文件是否已上传过
     */
    public function xmlExist() {
        foreach ($this->minioFileList as $key => $value) {
            $this->uploadXML(array_diff($this->localFileList[$key],$value));
        }
    }

    /**
     * 上传XML
     * @param array $path
     * @return void
     */
    public function uploadXML(array $path)
    {
        $this->result = [];
        foreach ($path as $value) {
            $this->minioService->putFile($value,$this->filePath.$value);
            $fileName = explode("/",$value);
            $fileInfo = explode("-",$fileName[1]);
            $data = [
                "file_name" => $fileName[1],
                "room_id" => $fileInfo[1],
                "file_path" => $value,
                "file_date" => $fileInfo[2],
                "file_read" => 0,
                "create_time"  => date("Y-m-d H:i:s"),
                "update_time"  => date("Y-m-d H:i:s")
            ];
            $this->result[] = $this->XMLModel->insertGetId($data);
            Log::info(date("Y-m-d H:i:s") . " $fileInfo[1] 上传成功");
        }
    }


    public function getXML() {

    }
}